package artid.com.arttogo.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v4.content.ContextCompat;
import android.util.Base64;
import android.util.Log;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageLoader.ImageListener;
import com.android.volley.toolbox.Volley;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import artid.com.arttogo.R;
import artid.com.arttogo.bean.HeadInfo;
import artid.com.arttogo.bean.PersonalCenter;
import artid.com.arttogo.bean.ShareItem;
import artid.com.arttogo.db.Cache;
import artid.com.arttogo.db.DataKeeper;
import artid.com.arttogo.fragment.BaseFragment;
import artid.com.arttogo.fragment.CollectionFragment;
import artid.com.arttogo.fragment.CommentFragment;
import artid.com.arttogo.network.AppUrl;
import artid.com.arttogo.network.AppUtil;
import artid.com.arttogo.network.BitmapCache;
import artid.com.arttogo.network.VolleyBasic;
import artid.com.arttogo.network.VolleyCallback;
import artid.com.arttogo.network.VolleyData;
import artid.com.arttogo.network.VolleyMap;
import artid.com.arttogo.utils.MySharedPreferences;
import artid.com.arttogo.utils.NetUtils;
import artid.com.arttogo.utils.ToastUtil;
import artid.com.arttogo.view.CircleImageView;

/**
 * 
 * 
 * 项目名称：ArtworkArtA 类名称：PersonalActivity
 * 类描述：个人信息 创建人：耿卫斌 创建时间：2016年5月16日
 * 下午2:29:38
 *
 */
public class PersonalActivity extends BaseFragment implements

		OnClickListener {
	private TextView mTitle;
	private RelativeLayout mPersonal_detail_layout;
	private TextView mNative_place;
	private TextView mUniversity;
	private RelativeLayout mRela_wdjz;

	private RelativeLayout mRela_wdsc;

	private RelativeLayout mRela_wdpl;

	private RelativeLayout mRela_tckb;

	private RelativeLayout mRela_hmkb;

	private RelativeLayout mRela_xx;

	private RelativeLayout mRela_gyysj;
	private RelativeLayout myOrderRL;

	private RelativeLayout mRela_jgrz;
	private RelativeLayout mRela_history;
	private RelativeLayout myNoteRL;
	private Intent mIntent;
	private ImageView photoImg;
	String path, baseImage;;
	Uri imgUri;
	Boolean isSetPic = false;
	private ImageLoader mImageLoader;
	Context mContext;
	private CircleImageView personalImage;
	TextView textName, textGz;
	private static final String IMAGE_FILE_LOCATION = "file:///sdcard/temp.jpg";
	Uri imageUri = Uri.parse(IMAGE_FILE_LOCATION);
	View mViewSetting, mViewATWD;
	ImageView imagedot,imagedot_message;
	private List<EMConversation> conversationList;
	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 1:
				conversationList.clear();
				conversationList.addAll(loadConversationsWithRecentChat());
				for (int i = 0; i < conversationList.size(); i++) {
					EMConversation conversation = EMClient.getInstance().chatManager().getConversation(conversationList.get(i).conversationId());
					unreadMesageNum=conversation.getUnreadMsgCount()+unreadMesageNum;
				}
				if (unreadMesageNum!=0) {
					imagedot_message.setVisibility(View.VISIBLE);
					//通知主界面
				}
				break;

			default:
				break;
			}
		};
	};
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
							 Bundle savedInstanceState) {
		conversationList = new ArrayList<EMConversation>();
		IntentFilter filter = new IntentFilter("com.PersonalActivity.receiver");
		getActivity().registerReceiver(broadcastReceiver, filter);

		View v = inflater.inflate(R.layout.activity_personal, null);
		mRela_history = (RelativeLayout)v.findViewById(R.id.rela_history);
		mRela_history.setOnClickListener(this);
		mRela_jgrz = (RelativeLayout)v.findViewById(R.id.rela_rzjg);
		mRela_jgrz.setOnClickListener(this);
		imagedot_message = (ImageView)v.findViewById(R.id.imagedot_message);
		imagedot = (ImageView) v.findViewById(R.id.image_per_dot);
		mViewATWD = (View) v.findViewById(R.id.rela_atwd);
		mViewATWD.setOnClickListener(this);
		mContext = getActivity().getApplicationContext();
		textName = (TextView) v.findViewById(R.id.native_place);
		textGz = (TextView) v.findViewById(R.id.university);
		personalImage = (CircleImageView) v.findViewById(R.id.personal_photo);
		personalImage.setOnClickListener(this);

		RequestQueue mQueue = Volley.newRequestQueue(getActivity());
		mImageLoader = new ImageLoader(mQueue, new BitmapCache());
		mTitle = (TextView) v.findViewById(R.id.title);
		mTitle.setText("个人中心");
		mPersonal_detail_layout = (RelativeLayout) v
				.findViewById(R.id.personal_detail_layout);
		mRela_wdjz = (RelativeLayout) v.findViewById(R.id.rela_wdjz);
		mRela_wdjz.setOnClickListener(this);
		mRela_wdsc = (RelativeLayout) v.findViewById(R.id.rela_wdsc);
		mRela_wdsc.setOnClickListener(this);
		mRela_wdpl = (RelativeLayout) v.findViewById(R.id.rela_wdpl);
		mRela_wdpl.setOnClickListener(this);
		mRela_tckb = (RelativeLayout) v.findViewById(R.id.rela_tckb);
		mRela_tckb.setOnClickListener(this);
		mRela_hmkb = (RelativeLayout) v.findViewById(R.id.rela_hmkb);
		mRela_hmkb.setOnClickListener(this);
		mRela_xx = (RelativeLayout) v.findViewById(R.id.rela_xx);
		mRela_xx.setOnClickListener(this);
		mRela_gyysj = (RelativeLayout) v.findViewById(R.id.rela_gyysj);
		mRela_gyysj.setOnClickListener(this);
		myNoteRL = (RelativeLayout) v.findViewById(R.id.rela_myNoteRL);
		myNoteRL.setOnClickListener(this);
		myOrderRL = (RelativeLayout) v.findViewById(R.id.Personal_myOrderRL);
		myOrderRL.setOnClickListener(this);
		mViewSetting = (View) v.findViewById(R.id.personal_setting);
		mViewSetting.setOnClickListener(this);
		return v;
	}

	int unreadMesageNum=0;
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

		reqData();
		refreshHxMessage();
	}

	/**
	 * 刷新环信会话列表
	 */
	public void refreshHxMessage() {
		new Thread(new Runnable() {
 
			@Override
			public void run() {
				// TODO Auto-generated method stub
				mHandler.sendEmptyMessage(1);
			}
		}).start();
	}
	public void selectFromAlbum() {
		File file = new File(imageUri.getPath());
		if (file.exists()) {
			file.delete();
		}
		Intent intent = new Intent(Intent.ACTION_PICK,
				android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		intent.setType("image/*");

		intent.putExtra("crop", "true");

		intent.putExtra("aspectX", 2);

		intent.putExtra("aspectY", 2);

		intent.putExtra("outputX", 600);

		intent.putExtra("outputY", 600);

		intent.putExtra("scale", true);

		intent.putExtra("return-data", false);

		intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);

		intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());

		intent.putExtra("noFaceDetection", true); // no face
		// detection

		startActivityForResult(intent, 2);
	}

	public void selectFromCamera() {
		// if (null != faceFile && faceFile.exists()) {
		// FileUtil.deleteFile(faceFile);
		// }
		// Uri imageUri = Uri.fromFile(new
		// File(Environment.getExternalStorageDirectory(),"image2.jpg"));
		File file = new File(imageUri.getPath());
		if (file.exists()) {
			file.delete();
		}
		Intent intent;
		intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
		// intent.putExtra("crop", "true");
		// intent.putExtra("aspectX", 1);// 瑁佸壀妗嗘瘮渚�
		// intent.putExtra("aspectY", 1);
		// intent.putExtra("outputX", 180);// 杈撳嚭鍥剧墖澶у皬
		// intent.putExtra("outputY", 180);
		// AppUtil.addOnActivatyResultListener(mOnActivityResultListener);
		// getActivity().startActivityForResult(intent,
		// IMAGE_REQUEST_CODE);
		startActivityForResult(intent, 1);

	}

	Bitmap photo;

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// /**使用SSO授权必须添加如下代码 */
		// if (data == null) {
		// return;
		// }
		switch (requestCode) {
		case 1:
			File file = new File(imageUri.getPath());
			if (!file.exists()) {
				return;
			}
			Intent intent = new Intent("com.android.camera.action.CROP");
			intent.setDataAndType(imageUri, "image/*");
			intent.putExtra("crop", "true");
			intent.putExtra("aspectX", 1);
			intent.putExtra("aspectY", 1);
			intent.putExtra("outputX", 300);
			intent.putExtra("outputY", 300);
			intent.putExtra("scale", true);
			intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);

			intent.putExtra("return-data", false);

			intent.putExtra("outputFormat",
					Bitmap.CompressFormat.JPEG.toString());

			intent.putExtra("noFaceDetection", true); // no face detection

			startActivityForResult(intent, 4);
			// personalImage.setImageBitmap(photo);

			break;

		case 2:
			// 判断是否从相册中获取图片
			if (data.getData() != null) {
				// 得到图片的全路径
				Uri uri = data.getData();
				imageUri=uri;
				File file2 = new File(imageUri.getPath());
				if (!file2.exists()) {
					return;
				}
			}
            setImage();
			break;

		case 3:
			Bundle bundle = data.getExtras();
			if (bundle != null) {
				if (photo != null && !photo.isRecycled()) {
					personalImage.setImageBitmap(null);
					photo.recycle();
					photo = null;
				}
				String imgPath = bundle.getString("imgPath");
				if (null == imgPath) {
					return;
				}
				photo = bundle.getParcelable("data");
				if (null == photo) {
					return;
				}

				reqIconModify(convertIconToString(photo));
			}
			break;
		case 4:
			File file2 = new File(imageUri.getPath());
			if (!file2.exists()) {
				return;
			}
			setImage();
			break;
		}

		super.onActivityResult(requestCode, resultCode, data);

	}

	Bitmap mapHead = null;;

	void setImage() {
		String sdStatus = Environment.getExternalStorageState();
		if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
			Log.v("TestFile", "SD card is not avaiable/writeable right now.");
			// Toast.makeText(this, "储存不可用，请检查", 300).show();
			return;
		}
		if (imageUri != null) {

			mapHead = decodeUriAsBitmap(imageUri);// decode bitmap

			// AppUtil.getUser().setIcon(bitmap);
			reqIconModify(convertIconToString(mapHead));
		}
	}

	private Bitmap decodeUriAsBitmap(Uri uri) {
		Bitmap bitmap = null;
		try {

			bitmap = BitmapFactory.decodeStream(mContext.getContentResolver()
					.openInputStream(uri));

		} catch (FileNotFoundException e) {

			e.printStackTrace();

			return null; 

		}

		return bitmap;

	}

	Boolean isModing = false;

	void reqIconModify(String base64) {
		VolleyBasic.getInstance(getActivity()).post(
				Cache.headInfo,
				VolleyMap.getInstance().headInfo(base64,
						AppUtil.getUser().getToken()), HeadInfo.class,

						new VolleyCallback() {

					@Override
					public void onSuccess(VolleyData vd) {
						// TODO Auto-generated method stub
						 HeadInfo info = (HeadInfo) vd.getData();
						if (vd.getCode() == 1) {
							personalImage.setImageBitmap(mapHead);	
							AppUtil.getUser().setHeadurl(info.getheadurl());
							DataKeeper.keepSerializable(getActivity(), AppUtil.getUser());
						}
					}      

					@Override
					public void onError(VolleyError volleyError) {
						// TODO Auto-generated method stub

					}
				});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.rela_history:
			Intent qrHis = new Intent(getActivity(), QRCodeHistoryActivity.class);
			startActivity(qrHis);
			break;
		case R.id.Personal_myOrderRL:
			//我的订单
			Intent myorderIntent = new Intent(getActivity(),OrderListActivity.class);
			startActivity(myorderIntent);
			break;

		case R.id.rela_atwd:
			Intent intentAtme = new Intent(getActivity(), ATmeActivity.class);
			startActivity(intentAtme);
			break;
		case R.id.personal_setting:
			Intent intent5 = new Intent(getActivity(), SettingActivity.class);
			startActivity(intent5);
			break;
		case R.id.rela_gyysj:

			Intent intentabout = new Intent(getActivity(), AboutUsActivity.class);
			startActivity(intentabout);

			break;
		case R.id.rela_hmkb:
			ToastUtil.toast(getActivity(), "敬请期待");
			break;

		case R.id.rela_tckb:
			ShareItem item2 = new ShareItem();
			Intent intent2 = new Intent(getActivity(), WebViewActivity.class);
			intent2.putExtra("type", AppUrl.LOAD_HOMEPAGE_WEB);
			intent2.putExtra("url", "http://www.ccloudb.com/");
			intent2.putExtra("share", item2);
			startActivity(intent2);
			break;
		case R.id.rela_wdjz:

			
			break;
		case R.id.rela_wdpl:
			Intent intent3 = new Intent(getActivity(), CommentFragment.class);
			startActivity(intent3);
			break;
		case R.id.rela_wdsc:
			Intent intent4 = new Intent(getActivity(), CollectionFragment.class);
			startActivity(intent4);
			break;
		case R.id.rela_xx:
			Intent intent6 = new Intent(getActivity(),
					PersonalMessageActivity.class);
			startActivity(intent6);
			break;

		case R.id.personal_photo:
			AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
			.setMessage("选择照片来源")
			.setPositiveButton("相机",
					new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface arg0,
						int arg1) {
					// TODO Auto-generated method stub
					//检查权限
					if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
						displayFrameworkBugMessageAndExit();
						return;
					}
					selectFromCamera();
				}
			})
			.setNegativeButton("取消",
					new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface arg0,
						int arg1) {
					// TODO Auto-generated method stub

				}
			})
			.setNeutralButton("相册",
					new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface arg0,
						int arg1) {
					// TODO Auto-generated method stub
					selectFromAlbum();
				}
			}).show();
			break;
		case R.id.rela_rzjg:
			Intent intent = new Intent(getActivity(),WebViewActivity.class);
			intent.putExtra("url",Cache.baseYanZhenUrl);
			intent.putExtra("type", AppUrl.LOAD_HOMEPAGE_WEB);
			startActivity(intent);
			break;
		case R.id.rela_myNoteRL:
			//我的笔记
			Intent intent7 = new Intent(getActivity(),AuctionMyNote_Activity.class);
			startActivity(intent7);
			break;
			
		default:
			break;
		}
	}
	
	MySharedPreferences sharedPreferences;

	void reqData() {
		// System.out.println("token=" + AppUtil.getUser().getToken());
		VolleyBasic.getInstance(getActivity()).post(
				Cache.personalCenter,
				VolleyMap.getInstance().personalCenter(
						AppUtil.getUser().getToken()), PersonalCenter.class,

						new VolleyCallback() {

					@Override
					public void onSuccess(VolleyData vd) {
						// TODO Auto-generated method stub
						if (vd.getCode() == -99) {
							AppUtil.Logout(mContext);
							AppUtil.LoginVer(getActivity());
							return;
						}
						PersonalCenter pc = (PersonalCenter) vd.getData();
						if (pc.getUserimg() != null) {
							sharedPreferences = sharedPreferences
									.getMySharedPreferences(mContext);
							sharedPreferences.setValue("person", vd.getJson());
							textName.setText( pc.getRealname());
							textGz.setText("关注 | " + pc.getFollownumber());

							ImageListener listener = ImageLoader
									.getImageListener(personalImage,
											R.drawable.head_sq,
											R.drawable.head_sq);
							mImageLoader.get(pc.getUserimg(), listener);
//														Animation animation = AnimationUtils.loadAnimation(mContext, R.anim.art_enter);
//														personalImage.startAnimation(animation);
							if (pc.getCommentread() == 1) {
								imagedot.setVisibility(View.VISIBLE);
							}else {
								imagedot.setVisibility(View.GONE);
							}
							if (pc.getSystemread()==1||unreadMesageNum!=0) {
								imagedot_message.setVisibility(View.VISIBLE);
							}else {
								imagedot_message.setVisibility(View.GONE);
							}
							if (pc.getCommentread() ==0&&pc.getSystemread()==0&&unreadMesageNum==0) {
								Intent intent2 =new Intent("com.MainActivity.receiver");
								intent2.putExtra("DotView", false);
								mContext.sendBroadcast(intent2);
							}else {
								Intent intent2 =new Intent("com.MainActivity.receiver");
								intent2.putExtra("DotView", true);
								mContext.sendBroadcast(intent2);
							}
						}

					}

					@Override
					public void onError(VolleyError volleyError) {
						// TODO Auto-generated method stub

					}
				});
	}

	// }

	/**
	 * 图片转成string
	 * 
	 * @param bitmap
	 * @return
	 */
	public static String convertIconToString(Bitmap bitmap) {
		ByteArrayOutputStream baos = new

				ByteArrayOutputStream();// outputstream
		bitmap.compress(CompressFormat.PNG, 100, baos);
		byte[] appicon = baos.toByteArray();// 转为byte数组
		return Base64.encodeToString(appicon,

				Base64.DEFAULT);
	}

	/**
	 * string转成bitmap
	 * 
	 * @param st
	 */
	public static Bitmap convertStringToIcon(String st) {
		// OutputStream out;
		Bitmap bitmap = null;
		try {
			// out = new FileOutputStream("/sdcard/aa.jpg");
			byte[] bitmapArray;
			bitmapArray = Base64.decode(st,

					Base64.DEFAULT);
			bitmap = BitmapFactory.decodeByteArray

					(bitmapArray, 0, bitmapArray.length);
			// bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
			return bitmap;
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 获取所有会话
	 *
	 * @return +
	 */
	private List<EMConversation> loadConversationsWithRecentChat() {
		// 获取所有会话，包括陌生人
		Map<String, EMConversation> conversations = EMClient.getInstance()
				.chatManager().getAllConversations();
		// 过滤掉messages size为0的conversation
		/**
		 * 如果在排序过程中有新消息收到，lastMsgTime会发生变化 影响排序过程，Collection.sort会产生异常
		 * 保证Conversation在Sort过程中最后一条消息的时间不变 避免并发问题
		 */
		List<Pair<Long, EMConversation>> sortList = new ArrayList<Pair<Long, EMConversation>>();
		synchronized (conversations) {
			for (EMConversation conversation : conversations.values()) {
				if (conversation.getAllMessages().size() != 0) {
					sortList.add(new Pair<Long, EMConversation>(conversation
							.getLastMessage().getMsgTime(), conversation));
				}
			}
		}
		try {
			// Internal is TimSort algorithm, has bug
			sortConversationByLastChatTime(sortList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		List<EMConversation> list = new ArrayList<EMConversation>();
		for (Pair<Long, EMConversation> sortItem : sortList) {
			list.add(sortItem.second);
		}
		for (int i = 0; i < list.size(); i++) {
			Log.d("log", "环信会话列表：" + list.get(i).getLastMessage().toString());
		}

		return list;
	}

	/**
	 * 根据最后一条消息的时间排序
	 *
	 */
	private void sortConversationByLastChatTime(
			List<Pair<Long, EMConversation>> conversationList) {
		Collections.sort(conversationList,
				new Comparator<Pair<Long, EMConversation>>() {
			@Override
			public int compare(final Pair<Long, EMConversation> con1,
					final Pair<Long, EMConversation> con2) {

				if (con1.first == con2.first) {
					return 0;
				} else if (con2.first > con1.first) {
					return 1;
				} else {
					return -1;
				}
			}

		});
	}


	BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context arg0, Intent arg1) {
			// TODO Auto-generated method stub
			if (arg1.getBooleanExtra("Umpush", false)||arg1.getBooleanExtra("Hxpush", false)) {
				imagedot_message.setVisibility(View.VISIBLE);
			};
		}
	};

	public void onDestroyView() {
		super.onDestroyView();
		getActivity().unregisterReceiver(broadcastReceiver);

	};

	/**
	 * 若摄像头被占用或者摄像头有问题则跳出提示对话框
	 */
	private void displayFrameworkBugMessageAndExit() {
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		builder.setTitle(getString(R.string.app_name));
		builder.setMessage("请设置开启摄像头权限");
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				NetUtils.getAppDetailSettingIntent(mContext);
			}
		});
		builder.show();
	}
}
